package com.itheima.app.gateway.filter;

import com.heima.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;

@Component//自动生效
@Slf4j//打日志
public class AuthFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1,获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2，校验当前请求路径是不是登录接口
        //2.1当前请求什么接口
        String path = request.getPath().toString();
        //2.2是不是登录接口
        if(path.contains("login")){
            //放行
            return chain.filter(exchange);
        }
        //3，获取请求头里面的token信息
        String token = request.getHeaders().getFirst("token");
        //4，判断token是否为空
        if(StringUtils.isEmpty(token)){
            //状态码设置
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //5，校验token有效性（JWT工具栏 ）
        Claims claimsBody =AppJwtUtil.getClaimsBody(token) ;
        int i = AppJwtUtil.verifyToken(claimsBody);
        if(i==1||i==2){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //6,放行
        return chain.filter(exchange);
    }
}
